package your.rpg.namespace;

import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
 
public class RpgActivity extends Activity{
	private Panel panel;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        try {
			panel = new Panel(this);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        setContentView(panel);
        panel.setOnTouchListener(new OnTouchListener() {  
            public boolean onTouch(View v,MotionEvent e) {  
            	int x = (int) e.getX();
            	int y = (int) e.getY();
               panel.handleInput(x,y);
               return false;
            }  
        });  
    }
 
    class Panel extends SurfaceView implements SurfaceHolder.Callback{
        private TutorialThread _thread;
        private LevelData _leveldata;
        private EventHandler _eventhandler;
        private LevelLoader _levelloader;
        private LevelFileReader _filereader;
        Paint paint = new Paint();
        private int startlevel = 0;
        private int currentlevel = 0;
        private String currentevent = "";
        private String actionMode = "move";
        int x1 = 0;//temp
        
        public Panel(Context context) throws IOException {
            super(context);
            getHolder().addCallback(this);
            _thread = new TutorialThread(getHolder(), this);  
            _leveldata = new LevelData();
            _levelloader = new LevelLoader(_leveldata);
            _filereader = new LevelFileReader(context,_levelloader);
            _eventhandler = new EventHandler(_leveldata);
            if(currentlevel == 0)
            {
            	_levelloader.processLevel("0");//after this load levels that are linked to it
            	currentlevel = startlevel;
            	currentevent = "event_start";
            	_eventhandler.setCurrentLevel(currentlevel);
            	_eventhandler.setCurrentEvent(currentevent);
            	_eventhandler.setPlaying();
            }
            paint.setColor(Color.BLACK);
        	paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            paint.setTextSize(20);
        }
        
        public void handleInput(int x, int y){
        		x1 = y;
        		if(_eventhandler.getAction().equals("text"))
        		{
        			nextEvent();
        		}
        		else if(_eventhandler.getAction().equals("text2"))
        		{
        			if(y >= 710)
        			{
        				_eventhandler.setSelectedOption(3);
        				_eventhandler.nextEventSkip(4);
        			}
        			else if(y < 710 && y >= 660)
        			{
        				_eventhandler.setSelectedOption(2);
        				_eventhandler.nextEventSkip(4);
        			}
        			else if(y < 660 && y >= 600)
        			{
        				_eventhandler.setSelectedOption(1);
        				_eventhandler.nextEventSkip(4);
        			}
        		}
        		else if(_eventhandler.getAction().equals("text3"))
        		{
        			_eventhandler.nextEventSkip(_eventhandler.getSkipAmount());
        		}
        }
        
        public void nextEvent(){
        		_eventhandler.nextEvent();
        }
 
        @Override
        public void onDraw(Canvas canvas) {
        	//check level to make sure correct data shown
        	currentlevel = _eventhandler.getCurrentLevel();
        	canvas.drawColor(Color.BLACK);
        	//draw background
            Bitmap background = BitmapFactory.decodeResource(getResources(),_leveldata.getBackground(currentlevel)); 
            canvas.drawBitmap(background, 0, 0, null);
            canvas.drawText(Integer.toString(x1), 300, 300,paint);
            //draw objects
            for(int i = _leveldata.getObjectAmount(currentlevel)-1; i>= 0; i--)
            {
            	Bitmap object = BitmapFactory.decodeResource(getResources(),_leveldata.getObjectImage(currentlevel, i));
            	canvas.drawBitmap(object, _leveldata.getObjectXpos(currentlevel, i), _leveldata.getObjectYpos(currentlevel, i), null);
            }
            //execute events
            _eventhandler.getNextEvent();
            //draw text if that is currentaction
            if(_eventhandler.getAction().equals("text") || _eventhandler.getAction().equals("text3"))
            {
            	Bitmap object = BitmapFactory.decodeResource(getResources(),0x7f020005);
            	canvas.drawBitmap(object, 0, 700, null);
	            canvas.drawText(_eventhandler.getActionContent(), 20, 725,paint);
            }
            //draw textoptions if currentaction = text2
            if(_eventhandler.getAction().equals("text2"))
            {
            	Bitmap object = BitmapFactory.decodeResource(getResources(),0x7f020005);
            	canvas.drawBitmap(object, 0, 700, null);
            	canvas.drawBitmap(object, 0, 650, null);
            	canvas.drawBitmap(object, 0, 600, null);
            	canvas.drawBitmap(object, 0, 550, null);
	            canvas.drawText(_eventhandler.getActionContent(), 20, 575,paint);
	            canvas.drawText(_eventhandler.getTextOption(1), 20, 625,paint);
	            canvas.drawText(_eventhandler.getTextOption(2), 20, 675,paint);
	            canvas.drawText(_eventhandler.getTextOption(3), 20, 725,paint);
            }
            //draw move or look buttons if no event playing
            if(_eventhandler.getPlayingEvent() == false)
            {
            	Bitmap button = BitmapFactory.decodeResource(getResources(),0x7f020000);
            	if(actionMode.equals("move"))
            	{//add levelnames to the boxes // add the correct names
            		canvas.drawBitmap(button,0,0,null);
            		if(_leveldata.getListSize("event_move1", currentlevel)>0)
            		{
                    	canvas.drawBitmap(button, 0, 640, null);
                    	canvas.drawText(_leveldata.getLevelName(_leveldata.getEventNameId(currentlevel,1)), 20, 700,paint);
            		}  
            		if(_leveldata.getListSize("event_move2", currentlevel)>0)
            		{
                    	canvas.drawBitmap(button, 160, 640, null);
                    	canvas.drawText(_leveldata.getLevelName(_leveldata.getEventNameId(currentlevel,2)), 180, 700,paint);
            		} 
            		if(_leveldata.getListSize("event_move3", currentlevel)>0)
            		{
                    	canvas.drawBitmap(button, 320, 640, null);
                    	canvas.drawText(_leveldata.getLevelName(_leveldata.getEventNameId(currentlevel,3)), 340, 700,paint);
            		} 
            	}
            }
        }
 
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // TODO Auto-generated method stub
 
        }
 
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            _thread.setRunning(true);
            _thread.start();
        }
 
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // simply copied from sample application LunarLander:
            // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
        }
    }
 
    class TutorialThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private Panel _panel;
        private boolean _run = false;
 
        public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }
 
        public void setRunning(boolean run) {
            _run = run;
        }
 
        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}